import cv2
from devicetest.aw.OpenHarmony import CommonOH, DeviceInfoHelper
from devicetest.core.test_case import Step

from .pom import DeskTop, KeyCode


def common_setup(device):
    Step('预置条件1：烧写目标版本后，正常进入桌面')
    try:
        CommonOH.checkIfTypeExist(device, 'Badge')
    except:
        CommonOH.goHome(device)
        # 点掉充电弹窗
        CommonOH.click(device, x=360, y=640)
        CommonOH.checkIfTypeExist(device, 'Badge')
    DeviceInfoHelper.setSleep(device, time_sleep=600)


def common_teardown(device, bundle_name=''):
    """
    通用teardown方法
    :param device:
    :param bundle_name:
    :return:
    """
    Step('收尾1：清理最近的任务回到桌面')
    CommonOH.sendKeyboardInputEvent(device, KeyCode.KEYCODE_HOME)
    CommonOH.click(device, **DeskTop.recent_button)
    CommonOH.click(device, **DeskTop.clear_button)
    if bundle_name:
        Step('收尾2：清除应用数据')
        CommonOH.cleanApplicationData(device, bundle_name)


def crop_picture(picture, x1=0, y1=80, x2=720, y2=1200):
    img = cv2.imread(picture)
    img = img[y1:y2, x1:x2]
    cv2.imwrite(picture, img)


def compare_image_similarity(image1, image2):
    image1 = cv2.imread(image1, 0)
    image2 = cv2.imread(image2, 0)

    # 初始化特征点检测器和描述符
    orb = cv2.ORB_create(edgeThreshold=5, patchSize=30)
    keypoints1, descriptors1 = orb.detectAndCompute(image1, None)
    keypoints2, descriptors2 = orb.detectAndCompute(image2, None)

    # 初始化匹配器
    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

    # 匹配特征点
    matches = bf.match(descriptors1, descriptors2)
    if not matches:
        return 0
    if not keypoints1:
        if not keypoints2:
            return 1
        return 0
    # 计算相似度
    similarity = len(matches) / len(keypoints1)

    return similarity
